package com.ffws.H08.api.schedule;

import com.ffws.H08.model.po.H08FireData;
import com.ffws.H08.utils.FtpUtil;
import com.ffws.H08.utils.FunctionUtil;
import com.ffws.base.model.RestResponse;
import com.mongodb.client.MongoCollection;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.csv.CSVRecord;
import org.apache.commons.net.ftp.FTPFile;
import org.bson.Document;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.io.IOException;
import java.time.LocalDate;
import java.util.*;
import static com.ffws.H08.system.SystemConstant.*;
import static com.ffws.H08.system.SystemConstant.MONGODB_H08_FIRE_DATA_COLLECTION_SUFFIX;

/**
 * @Author JC
 * @description 定时任务
 * @Date 2023-10-28 13:52
 * @Version 1.0
 */
@Slf4j
@Component
@EnableScheduling
@Api(value = "请求葵花八号卫星定时任务", tags = "请求葵花八号卫星定时任务")
public class ScheduleForH08ToMongoDB {

    @Resource
    private MongoTemplate mongoTemplate;

    /**
     * 从MongoBD中 删除 除今年之外的 卫星数据
     * 每年一月一号的 0:00:00 执行一次
     */
    @Scheduled(cron = "0 0 0 1 1 ?")
    public void deleteH08Data() {
        log.info("开启定时任务: 删除除今年之外的卫星数据");
        Set<String> collectionNames = mongoTemplate.getCollectionNames();
        int year = LocalDate.now().getYear();
        collectionNames.forEach(collectionName -> {
            if (Integer.parseInt(collectionName.substring(0,4)) < year) {
                mongoTemplate.dropCollection(collectionName);
            }
        });
        log.info("完成定时任务: 删除除今年之外的卫星数据");
    }

    /**
     * 开启定时任务: { 获取H08卫星数据 }
     * 每一分钟执行一次
     */
    @Scheduled(cron = "0 */1 * * * ?")
    public void getH08Data() {
        log.info("开启定时任务: 获取H08卫星数据");
        // 1.ftp获取最新数据
        Date date = new Date();
        date = new Date(date.getTime() - ONE_DAY);
        String format = FTP_H08_SDF.format(date);
        FTPFile[] ftpFiles;
        FTPFile finalFtpFile = null;
        while (true) {
            try {
                ftpFiles = FtpUtil.retrieveFTPFiles(FTP_H08 + format);
                if (ftpFiles.length > 0)  {
                    FTPFile[] files = FtpUtil.retrieveFTPFiles(FTP_H08 + format + "/" + ftpFiles[ftpFiles.length - 1].getName());
                    if (files.length > 0) {
                        Arrays.sort(files, new Comparator<FTPFile>() {
                            @Override
                            public int compare(FTPFile o1, FTPFile o2) {
                                Integer o1Time = Integer.valueOf(o1.getName().split("_")[2]);
                                Integer o2Time = Integer.valueOf(o2.getName().split("_")[2]);
                                return o1Time - o2Time;
                            }
                        });
                        finalFtpFile = files[files.length - 1];
                        break;
                    }
                }
                date = new Date(date.getTime() - ONE_DAY);
                format = FTP_H08_SDF.format(date);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        String finalFtpFilePath = FTP_H08 + format + "/" + ftpFiles[ftpFiles.length - 1].getName() + "/" + finalFtpFile.getName();
        log.info("finalFtpFilePath:{}",finalFtpFilePath);

        String[] s = finalFtpFile.getName().split("_");
        String collectionName = s[1] + s[2] + MONGODB_H08_FIRE_DATA_COLLECTION_SUFFIX;
        log.info("集合名称:{}", collectionName);

        List<H08FireData> h08FireDataList = new ArrayList<>();

        if (mongoTemplate.collectionExists(collectionName)) {
            MongoCollection<Document> collection = mongoTemplate.getCollection(collectionName);
            log.info("集合已存在,{}",collectionName);
            RestResponse.success(FunctionUtil.makeMongoH08DocToList(collection.find()));
            return;
        }

        List<CSVRecord> list = new ArrayList<>();
        try {
            list = FtpUtil.readCsvFile(finalFtpFilePath);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("读取csv文件失败");
        }
        // 2.从最新数据中解析出实体类
        list.remove(0);

        list.forEach(csv -> {
            H08FireData h08FireData = new H08FireData();
            h08FireData.setId(csv.get(0));
            h08FireData.setYear(Integer.valueOf(csv.get(1)));
            h08FireData.setMonth(Integer.valueOf(csv.get(2)));
            h08FireData.setDay(Integer.valueOf(csv.get(3)));
            h08FireData.setTime(csv.get(4));
            h08FireData.setLat(Float.valueOf(csv.get(5)));
            h08FireData.setLon(Float.valueOf(csv.get(6)));
            h08FireData.setArea(Float.valueOf(csv.get(7)));
            h08FireData.setLevel(Integer.valueOf(csv.get(9)));
            h08FireData.setReliability(Integer.valueOf(csv.get(10)));
            h08FireData.setHotId(csv.get(13));
            h08FireDataList.add(h08FireData);
        });

        // 3.创建集合
        if (!mongoTemplate.collectionExists(collectionName)) {
            mongoTemplate.createCollection(collectionName);
        }

        // 4.将实体类中的数据插入集合
        mongoTemplate.insert(h08FireDataList,collectionName);

        log.info("完成定时任务: 获取H08卫星数据");
    }

}
